<?php
declare (strict_types=1);

namespace app\admin\model\admin;

use app\admin\service\admin\User as AdminUserService;
use app\common\library\helper;
use app\common\model\admin\User as UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\Model;
use think\Paginator;

/**
 * 超管后台用户模型
 * Class User
 * @package app\admin\model\admin
 */
class User extends UserModel
{
    /**
     * 隐藏的字段
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    // 用户登录token
    private $token;

    /**
     * 获取列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->with(['role'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->paginate(10)->toArray();

        $list['data'] = $this->getRoleIds($list['data']);
        return $list;
    }

    private function getRoleIds($list)
    {
        foreach ($list as &$item) {
            if (!empty($item['role'])) {
                $item['roleIds'] = helper::getArrayColumn($item['role'], 'role_id');
            }
        }
        return $list;
    }
    public function getAllList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->select();
        return $list;
    }

    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'search' => '',
            'status' => -1,
        ]);

        $filter = [];
        !empty($params['search']) && $filter[] = ["user_name", "like", "%{$params['search']}%"];
        $params['status'] > -1 && $filter[] = ["status", "=", $params['status']];

        if (!empty($params['create_time'])) {
            $times = between_time($params['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    /**
     * 新增记录
     * @param array $data
     * @return bool
     */
    public function add(array $data, $admin)
    {
        $data['user_name'] = strtolower($data['user_name']);
        if (self::checkPhoneExist($data['phone'])) {
            $this->error = '手机号码已存在';
            return false;
        }

        if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }

        // 整理数据
        $data['password'] = encryption_hash($data['password']);

        $data['is_super'] = 0;

        // 事务处理
        $this->transaction(function () use ($data, $admin) {
            // 新增用户记录
            $this->save($data);
            // 新增角色关系记录
            UserRole::increased((int)$this['admin_user_id'], $data['role']);
//            // 新增部门记录
//            UserDepartment::increased((int)$this['admin_user_id'], $data['department']);

            OperationLog::recordLog('新增', "用户列表新增用户【{$data['user_name']}】", $admin['user']['admin_user_id']);
        });
        return true;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
        $data['user_name'] = strtolower($data['user_name']);

        if ($this['phone'] !== $data['phone'] && self::checkPhoneExist($data['phone'])) {
            $this->error = '手机号码已存在';
            return false;
        }
        if (!empty($data['password']) && ($data['password'] !== $data['password_confirm'])) {
            $this->error = '确认密码不正确';
            return false;
        }
        if (empty($data['role']) && !$this['is_super']) {
            $this->error = '请选择用户角色';
            return false;
        }
        if (!empty($data['password'])) {
            $data['password'] = encryption_hash($data['password']);
        } else {
            unset($data['password']);
        }

        $this->transaction(function () use ($data) {
            // 更新管理员记录
            $this->save($data);
            // 更新角色关系记录
            !$this['is_super'] && UserRole::updates((int)$this['admin_user_id'], $data['role']);
            // 新增部门关联记录
//            !$this['is_super'] && UserDepartment::updates((int)$this['admin_user_id'], $data['department']);
        });
        return true;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 批量软删除
     * @return false|int
     */
    public function batchSetDelete($ids)
    {
        return $this->where($this->getPk(), 'in', $ids)->save(['is_delete' => 1]);
    }

    /**
     * 超管后台用户登录
     * @param array $data
     * @return array|bool|null|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(array $data)
    {
        // 验证用户名密码是否正确
        if (!$user = $this->getUserInfoByLogin($data)) {
            $this->error = '登录失败, 手机号码或密码错误';
            return false;
        }
        if ($user->status) {
            $this->error = '登录失败, 当前账号已被停用';
            return false;
        }


        // 记录登录状态, 并记录token
        $this->token = AdminUserService::login($user->toArray());
        return $user;
    }

    public function phonelogin(array $data)
    {
        $key = 'login' . $data['phone'] . 'smscode';
        $code = Cache::get($key);
        if (empty($data['code']) || $data['code'] != $code) {
            $this->error = '登录失败, 验证码错误！';
            return false;
        }
        // 用户信息
        $user = static::withoutGlobalScope()
            ->where(['phone' => $data['phone']])
            ->where('is_delete', '=', 0)
            ->find();
        if (empty($user)) {
            $this->error = '登录失败, 当前手机未注册！';
            return false;
        }

        if ($user->status) {
            $this->error = '登录失败, 当前账号已被停用';
            return false;
        }

        //清除当前验证码
        Cache::delete($key);
        // 记录登录状态, 并记录token
        $this->token = AdminUserService::login($user->toArray());
        return $user;
    }

    public function resetPassword(array $data)
    {
        if ($data['password'] !== $data['confirm_password']) {
            $this->error = '确认密码不正确';
            return false;
        }
        $key = 'reset_password' . $data['phone'] . 'smscode';
        $code = Cache::get($key);
        if (empty($data['code']) || $data['code'] != $code) {
            $this->error = '提交失败, 验证码错误！';
            return false;
        }
        // 用户信息
        $user = static::withoutGlobalScope()
            ->where(['phone' => $data['phone']])
            ->where('is_delete', '=', 0)
            ->find();
        if (empty($user)) {
            $this->error = '提交失败, 当前手机未注册！';
            return false;
        }

        if ($user->status) {
            $this->error = '提交失败, 当前账号已被停用';
            return false;
        }

        //清除当前验证码
        Cache::delete($key);

        // 更新管理员信息
        if ($user->save([
                'password' => encryption_hash($data['password']),
            ]) === false) {
            return false;
        }
        return true;
    }

    /**
     * 获取登录的用户信息
     * @param $data
     * @return array|false|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getUserInfoByLogin(array $data)
    {
        $w = [];
        if (!empty($data['username'])) {
            $w['user_name'] = $data['username'];
        }
        if (!empty($data['phone'])) {
            $w['phone'] = $data['phone'];
        }

        // 用户信息
        $useInfo = static::withoutGlobalScope()
            ->where($w)
            ->where('is_delete', '=', 0)
            ->find();
        if (empty($useInfo)) return false;
        // 验证密码是否正确
        if (!password_verify($data['password'], $useInfo['password'])) {
            return false;
        }
        return $useInfo;
    }

    /**
     * 返回生成的token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * 更新当前管理员信息
     * @param $data
     * @return bool
     */
    public function renew(array $data)
    {
        if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }
        // 更新管理员信息
        if ($this->save([
                'user_name' => $data['user_name'],
                'password' => encryption_hash($data['password']),
            ]) === false) {
            return false;
        }
        // 更新登录信息
        AdminUserService::update($this->toArray());
        return true;
    }

}
